require 'net/https'
require 'cgi'
require 'rubygems'
require 'xmlsimple'
require 'sha1'
require 'time'
require 'yaml'

CONFIG = YAML::load_file('config.yml')
p CONFIG.inspect
open_id = CONFIG['open_id']
user_key = CONFIG['user_key']
app_key = CONFIG['app_key']
@http = Net::HTTP.new('api.springnote.com', 443)
@http.use_ssl = true

@username = CGI.escape(open_id)
@password = CGI.escape("#{user_key}.#{app_key}")

def get(page_id, file_path)
  p 'Getting....'
  @http.start do |http|
    req = Net::HTTP::Get.new("/pages/#{page_id}.xml")
    req.basic_auth @username, @password
    response = http.request(req)
    content = XmlSimple.xml_in(response.body)['source']
    p content
    File.open(file_path, 'w') {|f| f.write(content) }
  end
end

def put(page_id, file_path)
  p 'Putting....'
  @http.start do |http|
    req = Net::HTTP::Put.new("/pages/#{page_id}.xml", {'Content-Type' => 'application/xml'})
#    req.body = "<page><source><![CDATA[#{File.read(file_path)}]]></source></page>"
    req.body = "<page><source>#{CGI.escapeHTML(File.read(file_path))}</source></page>"
    req.basic_auth @username, @password
    response = http.request(req)
    p response.inspect
    content = XmlSimple.xml_in(response.body)['source']
    p content
  end
end

if ARGV[0] == 'get'
  get(ARGV[1], ARGV[2])
elsif ARGV[0] == 'put'
  put(ARGV[1], ARGV[2])
end